<template>
  <div class="department-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总共: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/employees/import')">导入 Excel</el-button>
          <el-button v-allow="'Export_excel'" type="error" size="small" @click="hExport">导出 Excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 20px">
        <el-table :data="employess">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{row}">
              <image-holder :src="row.staffPhoto" class="avatar" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              <!-- {{ row.formOfEmployment === 1 ? '正式' : '非正式' }} -->
              {{ formOfEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable>
            <template v-slot="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="text" @click="$router.push('/employees/detail/' + row.id)">查看</el-button>
              <!-- <el-button type="text" @click="$router.push(path: '/employees/ ', query: {id: row.id})">查看</el-button> -->
              <el-button type="text" @click="hAssign(row.id)">分配角色</el-button>
              <el-button type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="q.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="q.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <el-dialog
      :visible.sync="showDialog"
      title="新增员工"
      width="45%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="hClosed"
    >
      <emp-dialog ref="EmpDialog" @close="showDialog=false" @hSuccess="hSuccess" />
    </el-dialog>
    <el-dialog
      :visible.sync="showDialogRole"
      title="分配角色"
      width="45%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="$refs.assignRole.resetIds()"
    >
      <assignRole :id="curid" ref="assignRole" @close="showDialogRole=false" />
    </el-dialog>
  </div>
</template>

<script>
import { delEmployee, getsEmployess } from '@/api/employess'
import employessConst from '@/constant/employees'
import empDialog from './empDialog.vue'
import assignRole from './assignRole.vue'
import dayjs from 'dayjs'
// 准备一个映射对象, 最终目标是: { 1: '正式', 2: '非正式' }
const hireTypeMap = {}
// 可选作业: 把 forEach 变成 reduce
// 执行循环后达成目标: { 1: '正式', 2: '非正式' }
employessConst.hireType.forEach(item => {
  hireTypeMap[item.id] = item.value
})

export default {
  components: {
    empDialog,
    assignRole
  },
  data() {
    return {
      curid: '',
      employess: [],
      total: 0,
      q: {
        page: 1,
        size: 5
      },
      showDialog: false,
      showDialogRole: false
    }
  },
  created() {
    this.loadEmployess()
  },
  methods: {
    async loadEmployess() {
      const res = await getsEmployess(this.q)
      this.total = res.data.total
      this.employess = res.data.rows
    },
    formOfEmployment(code) {
      // // 去常量中找到对应的中文并返回
      // const result = employessConst.hireType.find(item => item.id === code)
      // // 提高代码的健壮性
      // if (result) {
      //   return result.value
      // } else {
      //   return '未知'
      // }

      return hireTypeMap[code]
    },
    handleCurrentChange(page) {
      this.q.page = page
      this.loadEmployess()
    },
    handleSizeChange(size) {
      this.q.size = size
      this.loadEmployess()
    },
    async hDel(id) {
      try {
        await this.$confirm('确认删除?', '提示', { type: 'warning' })
        const res = await delEmployee(id)
        this.$message.success(res.message)
        if (this.employess.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        this.loadEmployess()
      } catch (e) {
        // this.$message.error(e.message)
        // 精细化处理
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    hSuccess() {
      this.showDialog = false
      // 判断最后一夜是否满了
      if (this.total % this.q.size === 0) {
        this.total++
      }
      // 算出最后一页
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployess()
    },
    formatDate(data) {
      return dayjs(data).format('YYYY-MM-DD')
    },
    hClosed() {
      this.$refs.EmpDialog.resetForm()
    },
    async hExport() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1.发生请求获取所有的数据
      const res = await getsEmployess({ page: 1, size: this.total })
      // 去第一个数据
      const list = res.data.rows

      // 遍历zhlist将每个元素属性名转化为中文
      // const zhlist = list.map(enObj => {
      //   const zhObj = {}
      //   const enKeys = Object.keys(enObj)
      //   enKeys.forEach(enKey => {
      //     const zhKey = mapInfo[enKey]
      //     zhObj[zhKey] = enObj.enKey
      //   })
      //   return zhObj
      // })
      // console.log(zhlist)
      // const frist = zhlist[0]
      const frist = list[0]

      if (!frist) return
      // 取出 header
      const header = Object.keys(frist).map(enKey => mapInfo[enKey])
      const data = list.map(item => {
        const code = item['formOfEmployment']
        item['formOfEmployment'] = hireTypeMap[code]
        return Object.values(item)
      })
      console.log(data)
      // 2.导出 Excel (表头英文转中文)
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header, // 表头 传入一个数组
        data, // 数据 传入一个二维数组[[]], 二维数组里面的数组就是一条数据
        filename: '员工数据', // 导出的文件名称
        autoWidth: true, // 自适应宽度
        bookType: 'xlsx' // 文件类型
      })
    },
    hAssign(id) {
      // 把 id 传给子组件
      this.curid = id
      this.showDialogRole = true
      this.$nextTick(() => {
      // 调用子组件的 loadRoleIds 方法, 加载数据

        this.$refs.assignRole.loadRoleIds()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.el-pagination{
  display: flex;
  justify-content: center;
  height: 60px;
}
</style>
